package cc.cocosky.imclient;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Session {
	
	private Application application;
	private SocketChannel channel;
	private ByteBuffer buffer;
	private boolean lengReading;
	
	public Session(Application application, SocketChannel channel) {
		this.application = application;
		this.channel = channel;
		this.buffer = ByteBuffer.allocate(4);
		this.lengReading = true;
	}
	
	public ByteBuffer getBuffer() {
		return buffer;
	}
	
	private void resetBuffer(int capacity) {
		buffer = ByteBuffer.allocate(capacity);
	}
	
	void read() throws IOException {
		int len = channel.read(buffer);
		if(len == -1) {
			System.err.println("disconnected : " + channel.getRemoteAddress() + "\n");
			application.killSession(channel);
			return;
		}
		if(!buffer.hasRemaining()) {
			if(lengReading) {
				buffer.flip();
				int length = buffer.getInt();
				resetBuffer(length);
				lengReading = false;
				read();
			} else {
				
				System.out.println("Readed : " + new String(buffer.array()));
				
				resetBuffer(4);
				lengReading = true;
			}
		}
	}
	
	public void write(ByteBuffer data) throws IOException {
		ByteBuffer buffer;
		if(data != null) {
			data.mark();
			int length = data.remaining();
			buffer = ByteBuffer.allocate(4 + length);
			buffer.putInt(length);
			buffer.put(data);
			data.reset();
		} else {
			buffer = ByteBuffer.allocate(4);
			buffer.putInt(0);
		}
		buffer.flip();
		channel.write(buffer);
	}
	
	public void write(byte[] data) throws IOException {
		ByteBuffer buffer = ByteBuffer.wrap(data);
		write(buffer);
	}
	
	public void destory() {
		buffer = null;
		channel = null;
		application = null;
	}
	

}
